const UserModel = require('../models/UserModel')

const UserService = {
  login: async ({ username, password }) => {
    return UserModel.find({
      username,
      password
    })
  },

  upload: async ({ _id, phone, email, avatar }) => {
    if (avatar) {
      return UserModel.updateOne(
        { _id },
        {
          phone,
          email,
          avatar
        }
      )
    } else {
      return UserModel.updateOne(
        { _id },
        {
          phone,
          email
        }
      )
    }
  },

  add: async ({ username, password, name, gender, role, phone, email, avatar }) => {
    if (avatar) {
      return UserModel.create({
        username,
        password,
        name,
        gender,
        role,
        phone,
        email,
        avatar
      })
    } else {
      return UserModel.create({
        username,
        password,
        name,
        gender,
        role,
        phone,
        email
      })
    }
  },

  getList: async ({ id }, { username }, page, limit) => {
    if (id) {
      return UserModel.find({ _id: id }, ['username', 'password', 'name', 'gender', 'role', 'phone', 'email'])
    } else {
      if (username) {
        return UserModel.find({ username, $or: [{ role: 1 }, { role: 2 }] }, ['username', 'name', 'gender', 'role', 'phone', 'email', 'avatar'])
          .sort({ _id: -1 })
          .skip((page - 1) * limit)
          .limit(limit)
      } else {
        return UserModel.find({ $or: [{ role: 1 }, { role: 2 }] }, ['username', 'name', 'gender', 'role', 'phone', 'email', 'avatar'])
          .sort({ _id: -1 })
          .skip((page - 1) * limit)
          .limit(limit)
      }
    }
  },

  delList: async ({ _id }) => {
    return UserModel.deleteOne({ _id })
  },

  putList: async (body) => {
    return UserModel.updateOne({ _id: body._id }, body)
  },

  getTeacherList: async () => {
    return UserModel.find({ role: 2 }, ['username', 'name'])
  },

  getStudentList: async ({ username }, page, limit) => {
    if (username) {
      return UserModel.find({ username, role: 3 }, ['username', 'name', 'gender', 'role', 'phone', 'email', 'avatar'])
        .sort({ username: -1 })
        .skip((page - 1) * limit)
        .limit(limit)
    } else {
      return UserModel.find({ role: 3 }, ['username', 'name', 'gender', 'role', 'phone', 'email', 'avatar'])
        .sort({ username: -1 })
        .skip((page - 1) * limit)
        .limit(limit)
    }
  },

  getTotal: async ({ username }) => {
    if (username) {
      return UserModel.countDocuments({ username, $or: [{ role: 1 }, { role: 2 }] })
    } else {
      return UserModel.countDocuments({ $or: [{ role: 1 }, { role: 2 }] })
    }
  },

  getStudentTotal: async ({ username }) => {
    if (username) {
      return UserModel.countDocuments({ username, role: 3 })
    } else {
      return UserModel.countDocuments({ role: 3 })
    }
  }
}

module.exports = UserService
